#include "mainwindow.h"
#include <QApplication>
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QDir>
#include <QTextStream>

QMutex mutex;

// 自定义log处理函数
void customMessageHandler(
    QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static bool system_up = false;
    if (!system_up)
    {
        // crete folder path
        QDir folder_path(QCoreApplication::applicationDirPath()); // 初始化为当前目录
        bool exist = folder_path.exists("log");
        if (!exist)
        {
            folder_path.mkdir("log");
        }
        else
        {
            QString filePath = QCoreApplication::applicationDirPath() + "/log/";
            QDir dir(filePath);
            QFileInfoList fileList = dir.entryInfoList();
            QDateTime present_date = QDateTime::currentDateTime();
            for (QFileInfo info : fileList)
            { // 遍历指定目录
                // 按条件删除文件
                QDateTime log_time = QDateTime::fromString(info.fileName().left(10), "yyyy-MM-dd");
                if (log_time.isValid())
                {
                    int days = log_time.daysTo(present_date);
                    if (days > 30)
                    { // 超过30天删除
                        QFile(info.absoluteFilePath()).remove();
                    }
                }
            }
        }
        system_up = true;
    }

    // 输出到文件
    QString message = qFormatLogMessage(type, context, msg);
    mutex.lock();
    QFile file(QCoreApplication::applicationDirPath() + "/log/" +
               qPrintable(QDateTime::currentDateTime().toString("yyyy-MM-dd")) + ".log");
    if (file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream text_stream(&file);
        text_stream << message << Qt::endl;
        file.close();
    }
    mutex.unlock();
}

int main(
    int argc, char *argv[])
{
    QApplication a(argc, argv);
    qSetMessagePattern(
        "%{time yyyy-MM-dd hh:mm:ss.zzz} [%{type}] %{pid} %{threadid} " "%{file}:%{line} " "%{" "fu" "nc" "ti" "o" "n}(): " "%{message}");
// 注册自定义函数
#ifdef QT_NO_DEBUG
    qInstallMessageHandler(customMessageHandler);
#endif
    MainWindow w;
    w.show();
    return a.exec();
}
